import React, { Component } from 'react'
import { connect } from 'dva';
import moment from 'moment';
import { Form, Input, Select, DatePicker, Modal, message } from 'antd';
import { SearchRow, SearchCol, SearchButton } from '@/styled/form';
import { DICT } from '../enum';
import Link from 'umi/link';
import { rulesRemove } from '../service';
import { DropDownSelect } from '@/components/DropDownSelect/index';
import { relusEnable, relusDisable } from '@/pages/data/unit_task_rules/service';

const { RangePicker } = DatePicker;
const { confirm } = Modal;

interface Props {
  current: number,
  form: any,
  dispatch?: Function,
  changeOption?: Function,
  removeOption?: Function,
  initCurrent: Function,
  dict?: Object,
  userIdList?: any,
  rowDatas?: any,
  cond?: any
}

const FormItem = Form.Item;
const ONE_PAGE_SIZE = 10;

@connect(({ unit_task_rules }) => ({
  dict: unit_task_rules.dict,
  cond: unit_task_rules.cond
}))
class Search extends Component<Props, any> {
  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'unit_task_rules/queryDict',
      payload: {
        keyList: DICT
      }
    }).then(() => {
      const { cond, form } = this.props;
      const { pageNum, pageSize, ...searchParams } = cond;
      form.setFieldsValue(searchParams);
    });

    dispatch({
      type: 'unit_task_rules/queryDictList'
    })
  }

  queryData = (offset = 1, size = ONE_PAGE_SIZE) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'unit_task_rules/queryPage',
      payload: {
        pageNum: offset,
        pageSize: size,
        resType: '1'
      },
    });
  };

  delConfirm = () => { // 删除
    let that = this;
    let idList = that.props.userIdList;
    if (idList.length === 0) {
      message.warning('请选择后操作', 1.5);
      return;
    }
    confirm({
      title: '删除',
      content: '是否删除？',
      onOk() {
        let params = {
          idList
        };
        let tipMsg = message.loading('');
        rulesRemove(params).then((data) => {
          tipMsg();
          if (data !== undefined) {
            message.success('操作成功', 1.5);
            that.props.removeOption('ok');
            that.queryData();
          }
        }, () => {
          tipMsg();
          message.warning('操作失败', 1.5);
        });
      },
      onCancel() { },
      okText: "确认",
      cancelText: "取消"
    });
  };

  startFn() { // 启用
    let that = this;
    let tit = '模板启用';
    let txt = '确定启用该任务规则？';
    let idList = that.props.userIdList;
    if (idList.length === 0) {
      message.warning('请选择后操作', 1.5);
      return;
    }
    let rowDatas = that.props.rowDatas.map(item => {
      let obj = { id: item.id, status: item.status };
      return obj;
    });
    let isAllStatus = false;
    rowDatas.forEach(item => {
      if (item.status === '1') {
        isAllStatus = true;
      }
    });
    if (isAllStatus) {
      message.warning('存在不可启用项', 1.5);
      return;
    }
    confirm({
      title: tit,
      content: txt,
      onOk() {
        let hasMsg = message.loading('');
        relusEnable({ idList }).then((data) => {
          hasMsg();
          if (data === undefined) {
            return;
          }
          message.success('操作成功', 1);
          that.props.changeOption();
          that.queryData();
        });
      },
      onCancel() { },
      okText: "确认",
      cancelText: "取消"
    });
  }
  endFn() {
    let that = this;
    let tit = '模板停用';
    let txt = '确定停用该任务规则？';
    let idList = that.props.userIdList;
    if (idList.length === 0) {
      message.warning('请选择后操作', 1.5);
      return;
    }
    let rowDatas = that.props.rowDatas.map(item => {
      let obj = { id: item.id, status: item.status };
      return obj;
    });
    let isAllStatus = false;
    rowDatas.forEach(item => {
      if (item.status === '0') {
        isAllStatus = true;
      }
    });
    if (isAllStatus) {
      message.warning('存在不可停止项', 1.5);
      return;
    }
    confirm({
      title: tit,
      content: txt,
      onOk() {
        let hasMsg = message.loading('');
        relusDisable({ idList }).then(() => {
          hasMsg();
          message.success('操作成功', 1);
          that.props.changeOption();
          that.queryData();
        });
      },
      onCancel() { },
      okText: "确认",
      cancelText: "取消"
    });
  }

  search = e => {
    e.preventDefault();
    const { dispatch } = this.props;
    this.props.form.validateFields((err, values) => {
      if (!!values.endTime) {
        values.endTimeStart = moment(values.endTime[0]._d).format("YYYY-MM-DD");
        values.endTimeEnd = moment(values.endTime[1]._d).format("YYYY-MM-DD");
      }
      delete values.endTime;
      if (!err) {
        dispatch({
          type: 'unit_task_rules/updateCond',
          payload: {
            resType: '1',
            ...values
          }
        });

        this.props.initCurrent()
      }
    });
  };

  render() {
    const { form, dict } = this.props;
    const { getFieldDecorator } = form;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    };
    return (
      <Form onSubmit={this.search}>
        <SearchRow>
          <SearchCol key={0} span={4}>
            <FormItem
              label="规则名称"
              {...formItemLayout}
            >
              {getFieldDecorator('name', {
                rules: [{ message: '输入规则名称' }],
              })(
                <Input placeholder="请输入规则名称" />
              )}
            </FormItem>
          </SearchCol>
          <SearchCol key={1} span={3}>
            <FormItem
              label="任务类型"
              {...formItemLayout}
            >
              {dict['rules.taskType'] ? getFieldDecorator('taskType', {
                rules: [{ message: '输入任务类型' }],
              })(
                DropDownSelect(dict, 'rules.taskType')
              ) : null}
            </FormItem>
          </SearchCol>
          <SearchCol key={2} span={3}>
            <FormItem
              label="状态"
              {...formItemLayout}
            >
              {getFieldDecorator('status', {
                rules: [{ message: '输入状态' }],
              })(
                DropDownSelect(dict, 'rules.state')
              )}
            </FormItem>
          </SearchCol>
          <SearchCol key={4} span={4}>
            <FormItem
              label="截止时间"
              {...formItemLayout}
            >
              {getFieldDecorator('endTime')(
                <RangePicker
                  format="YYYY-MM-DD"
                  placeholder={['开始日期', '结束日期']}
                />
              )}
            </FormItem>
          </SearchCol>
          <SearchCol key={9} span={10}>
            <SearchRow type="flex" justify="end" style={{ marginTop: '-5px' }}>
              <SearchButton htmlType="submit">搜索</SearchButton>
              <SearchButton onClick={(e) => {
                this.props.form.resetFields();
                this.search(e)
              }} style={{ 'marginLeft': '15px' }}>重置</SearchButton>
              <Link to='/data/unit_task_rules/new_task_rules'><SearchButton icon='plus'>新增规则</SearchButton></Link>
              <SearchButton icon='minus' onClick={this.delConfirm}>删除规则</SearchButton>
              <SearchButton onClick={this.startFn.bind(this)}>启用</SearchButton>
              <SearchButton onClick={this.endFn.bind(this)}>停止</SearchButton>
            </SearchRow>

          </SearchCol>
        </SearchRow>
      </Form>
    );
  }
}

const SearchS = Form.create()(Search);
export default SearchS;
